package com.xfhy.selectcity.select;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.ludashi.framework.adapter.BaseQuickAdapter;
import com.ludashi.framework.base.BaseFrameActivity;
import com.xfhy.selectcity.R;
import com.xfhy.selectcity.adapter.SelectCityAdapter;
import com.xfhy.selectcity.select.viewmodel.SelectCityViewModel;

import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 选则城市
 */
public class SelectCityActivity extends BaseFrameActivity implements BaseQuickAdapter.OnItemClickListener {

    private final static String PROVINCE_NAME_KEY = "province_name";

    private RecyclerView mRvSelectCity;
    private SelectCityViewModel mSelectCityViewModel;
    private List<String> mCityItems = new ArrayList<>();
    private SelectCityAdapter mSelectCityAdapter;

    public static void startSelectCityActivity(Context context, String provinceName) {
        Intent intent = new Intent(context, SelectCityActivity.class);
        intent.putExtra(PROVINCE_NAME_KEY, provinceName);
        context.startActivity(intent);
    }

    @Override
    protected void onSafeCreate(Bundle savedInstanceState) {
        super.onSafeCreate(savedInstanceState);
        setContentView(R.layout.activity_select_city);

        initView();
        initData();
    }

    private void initView() {
        mRvSelectCity = findViewById(R.id.rv_select_city);

        mSelectCityAdapter = new SelectCityAdapter(null);
        mRvSelectCity.setAdapter(mSelectCityAdapter);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mRvSelectCity.setLayoutManager(gridLayoutManager);
    }

    private void initData() {
        mSelectCityViewModel = new ViewModelProvider(this).get(SelectCityViewModel.class);
        mSelectCityViewModel.queryCitiesByProvince(getIntent().getStringExtra(PROVINCE_NAME_KEY)).observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> areas) {
                mCityItems = areas;
                mSelectCityAdapter.replaceData(mCityItems);
            }
        });
        mSelectCityAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
        String city = mCityItems.get(position);
        SelectAreaActivity.startSelectAreaActivity(this, city);
    }
}